--[[
Copyright 2008, 2009, 2010, 2011 João Cardoso
Scrap is distributed under the terms of the GNU General Public License (or the Lesser GPL).
This file is part of Scrap.

Scrap is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Scrap is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Scrap. If not, see <http://www.gnu.org/licenses/>.
--]]

local Tooltip = CreateFrame('GameTooltip', 'ScrapTooltip', nil, 'GameTooltipTemplate')
local Scrap = CreateFrame('Button', 'Scrap', MerchantBuyBackItem)
local Unusable, ActualSlots = Scrap_Unusable, Scrap_ActualSlots

local WEAPON, ARMOR, _, CONSUMABLES = GetAuctionItemClasses()
local CAN_TRADE = BIND_TRADE_TIME_REMAINING:format('.*')
local MATCH_CLASS = ITEM_CLASSES_ALLOWED:format('')
local CLASS_NAME = Scrap_Class


--[[ Events ]]--

function Scrap:Startup()
	self:SetScript('OnEvent', function(self, event) self[event](self) end)
	self:RegisterEvent('MERCHANT_SHOW')
end

function Scrap:MERCHANT_SHOW()
	if not LoadAddOn('Scrap_Merchant') then
		self:UnregisterEvent('MERCHANT_SHOW')
	else
		self:MERCHANT_SHOW()
	end
end


--[[ List API ]]--

function Scrap:IsJunk(itemID)
	if itemID then
		local _, itemLink, itemQuality, itemLevel, _, itemType, itemSubType, _, itemSlot, _, itemValue = GetItemInfo(itemID)
		local isJunk = itemQuality == ITEM_QUALITY_POOR and itemValue > 0
		
		if Scrap_LowConsume and itemType == CONSUMABLES then
			isJunk = itemLevel ~= 0 and (UnitLevel('player') - itemLevel) > 10
			
		elseif itemType == ARMOR or itemType == WEAPON then
			if isJunk then
				isJunk = itemLevel > 10
			else
				if not self:IsEnchanter() then
					Tooltip:SetOwner(UIParent, 'ANCHOR_NONE')
					Tooltip:SetHyperlink(itemLink)
					
					local numLines = Tooltip:NumLines()
					local lastLine = _G['ScrapTooltipTextLeft'..numLines]:GetText()
					
					if not strmatch(lastLine, CAN_TRADE) then
						for i = 2,4 do
							if _G['ScrapTooltipTextLeft'..i]:GetText() == ITEM_BIND_ON_PICKUP then
								local unusable = Unusable[itemSubType] or itemSlot == 'INVTYPE_WEAPONOFFHAND' and Unusable[3]
								if unusable or self:IsLowEquip(itemID, itemSubType, itemSlot, itemLevel, itemQuality) then
									isJunk = true
								else
									for i = numLines, i, -1 do
										local text = _G['ScrapTooltipTextLeft'..i]:GetText()
										if strmatch(text, MATCH_CLASS) then
											isJunk = not strmatch(text, CLASS_NAME)
											break
										end
									end
								end
								break
							end
						end
					end
				end
			end
		end
		
		if Scrap_List[itemID] then
			isJunk = not isJunk
		end
		return isJunk
	end
end

function Scrap:IterateJunk()
	local bagNumSlots, bag, slot = GetContainerNumSlots(BACKPACK_CONTAINER), BACKPACK_CONTAINER, 0
	local match, id
	
	return function()
		match = nil
		
		while not match do
			if slot < bagNumSlots then
				slot = slot + 1
			elseif bag < NUM_BAG_FRAMES then
				bag = bag + 1
				bagNumSlots = GetContainerNumSlots(bag)
				slot = 1
			else
				bag, slot = nil
				break
			end
			
			id = GetContainerItemID(bag, slot)
			match = self:IsJunk(id)
		end
		
		return bag, slot, id
	end
end

function Scrap:GetJunkValue()
    local value = 0
    for bag, slot, id in self:IterateJunk() do
    	local stack, locked = select(2, GetContainerItemInfo(bag, slot))
    	local itemValue = select(11, GetItemInfo(id))
    	
    	if not locked and itemValue then
			value = value + itemValue * stack
		end
	end
	return value
end


--[[ Status API ]]--

function Scrap:IsEnchanter()
	local prof1, prof2 = GetProfessions()
	return not prof1 or not prof2 or select(7, GetProfessionInfo(prof1)) == 333 or select(7, GetProfessionInfo(prof2)) == 333
end

function Scrap:IsLowEquip(itemID, itemSubType, itemSlot, itemLevel, itemQuality) -- for "Pawn Scrap" to change
	if Scrap_LowEquip and itemSlot ~= '' and itemSubType ~= 'Fishing Poles' then
		local slot = strmatch(itemSlot, 'INVTYPE_(.+)')
		
		if slot ~= 'TRINKET' and slot ~= 'TABARD' and slot ~= 'BODY' then
			local value, double = itemLevel * itemQuality^.35
			local slot1, slot2 = ActualSlots[slot] or slot
			
			if slot1 == 'WEAPON' or slot1 == '2HWEAPON' then
				if slot1 == '2HWEAPON' then
					double = true
				end
				
				slot1, slot2 = 'MAINHAND', 'OFFHAND'
			elseif slot1 == 'FINGER' then
				slot1, slot2 = 'FINGER1', 'FINGER2'
			end
			
			return self:HasBetterEquip(slot1, value) and (not slot2 or self:HasBetterEquip(slot2, value, double))
		end
	end
end

function Scrap:HasBetterEquip(slot, value, empty)
	local equipedItem = GetInventoryItemID('player', _G['INVSLOT_'..slot])
	if equipedItem then
		local _,_, equipQuality, equipLevel = GetItemInfo(equipedItem)
		return equipLevel * equipQuality^.35 - value > 15
	elseif empty then
		return true
	end
end


--[[ Call Addon ]]--

Scrap:Startup()